/*global define:true $:true _:true*/

define(function () {
	"use strict";

    var exports = {},
		minimimValidPasswordLength = 8,
		validate, reset, markAsValid, markAsInvalid, passwordPolicyRuleIsValid,
		hasValidLength, hasAtLeast1Uppercase, hasAtLeast1Lowercase, hasAtLeast1Number, hasAtLeast1SpecialChar;

	validate = function(val, $passwordValidStatusIndicator, passwordPolicyFields) {
		reset(passwordPolicyFields);

		var isValid = hasValidLength(val, passwordPolicyFields.mustHaveAtLeast8Chars) &
			hasAtLeast1Uppercase(val, passwordPolicyFields.mustHaveAtLeast1Uppercase) & 
			hasAtLeast1Lowercase(val, passwordPolicyFields.mustHaveAtLeast1Lowercase) & 
			hasAtLeast1Number(val, passwordPolicyFields.mustHaveAtLeast1Number) & 
			hasAtLeast1SpecialChar(val, passwordPolicyFields.mustHaveAtLeast1SpecialChar);

		if (isValid){
			markAsValid($passwordValidStatusIndicator);
		} else {
			markAsInvalid($passwordValidStatusIndicator);
		}
	};

	reset = function(passwordPolicyFields){
		_.each(passwordPolicyFields, function($field){
			$field.css('color', 'red');
		});
	};

	hasValidLength = function(val, $field){
		if (val.length >= minimimValidPasswordLength) return passwordPolicyRuleIsValid($field);
		return false;
	};

	hasAtLeast1Uppercase = function(val, $field){
		if (/[A-Z]/.test(val)) return passwordPolicyRuleIsValid($field);
		return false;
	};
	
	hasAtLeast1Lowercase = function(val, $field){
		if (/[a-z]/.test(val)) return passwordPolicyRuleIsValid($field);
		return false;
	};

	hasAtLeast1Number = function(val, $field){
		if (/[0-9]/.test(val)) return passwordPolicyRuleIsValid($field);
		return false;
	};

	hasAtLeast1SpecialChar = function(val, $field){
		if (/[~!@#$\^&*()-+\\]/.test(val)) return passwordPolicyRuleIsValid($field);
		return false;
	};

	passwordPolicyRuleIsValid = function($field){
		$field.css('color', 'green');
		return true;
	};

	markAsValid = function($field){
		$field.animate({
			backgroundColor: "green"
		}, "slow");
	};
	
	markAsInvalid = function($field){
		$field.animate({
			backgroundColor: "red"
		}, "slow");
	};

    exports.exec = function ($password) {
		var $passwordValidStatusIndicator = $(".password-valid-status-indicator"),
			passwordPolicyFields = {
				mustHaveAtLeast8Chars: $("#MustHaveAtLeast8Chars"),
				mustHaveAtLeast1Uppercase: $("#MustHaveAtLeast1Uppercase"),
				mustHaveAtLeast1Lowercase: $("#MustHaveAtLeast1Lowercase"),
				mustHaveAtLeast1Number: $("#MustHaveAtLeast1Number"),
				mustHaveAtLeast1SpecialChar: $("#MustHaveAtLeast1SpecialChar")
			};

		$password.keyup(function () {
			validate($password.val(), $passwordValidStatusIndicator, passwordPolicyFields);
		});

		if ($password.val() > 0)
		    validate($password.val(), $passwordValidStatusIndicator, passwordPolicyFields);
	};

	return exports;
});